<!DOCTYPE html>
<html lang="zh-hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/wow/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/wow/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/wow/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/wow/images/logo.svg" color="#222">

<link rel="stylesheet" href="/wow/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.3/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"single-flower.gitee.io","root":"/wow/","images":"/wow/images","scheme":"Muse","version":"8.3.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"بحث...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}};
  </script>
<meta name="description" content="安装包pip3 install Django&#x3D;&#x3D;2.2 pip3 install celery&#x3D;&#x3D;4.4.7 pip install redis&#x3D;3.5.3 今天我们以手机号发送短信为例子 具体代码如下在settings中的INSTALLED_APPS里配置djcelery以及消息列队的地址123456# settings.pyimport djcelerydjcelery.setup_loade">
<meta property="og:type" content="article">
<meta property="og:title" content="celery异步框架">
<meta property="og:url" content="https://single-flower.gitee.io/wow/2021/02/03/zy/celery%E5%BC%82%E6%AD%A5%E6%A1%86%E6%9E%B6(5.0)/index.html">
<meta property="og:site_name" content="朵朵最可爱">
<meta property="og:description" content="安装包pip3 install Django&#x3D;&#x3D;2.2 pip3 install celery&#x3D;&#x3D;4.4.7 pip install redis&#x3D;3.5.3 今天我们以手机号发送短信为例子 具体代码如下在settings中的INSTALLED_APPS里配置djcelery以及消息列队的地址123456# settings.pyimport djcelerydjcelery.setup_loade">
<meta property="og:locale">
<meta property="article:published_time" content="2021-02-03T02:26:02.419Z">
<meta property="article:modified_time" content="2021-04-13T07:05:36.155Z">
<meta property="article:author" content="X y">
<meta property="article:tag" content="-GIT">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://single-flower.gitee.io/wow/2021/02/03/zy/celery%E5%BC%82%E6%AD%A5%E6%A1%86%E6%9E%B6(5.0)/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-hans'
  };
</script>
<title>celery异步框架 | 朵朵最可爱</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="تشغيل شريط التصفح" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/wow/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">朵朵最可爱</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/wow/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a></li>
        <li class="menu-item menu-item-about"><a href="/wow/about/" rel="section"><i class="fa fa-user fa-fw"></i>معلومات</a></li>
        <li class="menu-item menu-item-tags"><a href="/wow/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>الوسوم</a></li>
        <li class="menu-item menu-item-categories"><a href="/wow/categories/" rel="section"><i class="fa fa-th fa-fw"></i>التصنيفات</a></li>
        <li class="menu-item menu-item-archives"><a href="/wow/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>الأرشيفات</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          المحتويات
        </li>
        <li class="sidebar-nav-overview">
          عام
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%89%E8%A3%85%E5%8C%85"><span class="nav-number">1.</span> <span class="nav-text">安装包</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BB%8A%E5%A4%A9%E6%88%91%E4%BB%AC%E4%BB%A5%E6%89%8B%E6%9C%BA%E5%8F%B7%E5%8F%91%E9%80%81%E7%9F%AD%E4%BF%A1%E4%B8%BA%E4%BE%8B%E5%AD%90-%E5%85%B7%E4%BD%93%E4%BB%A3%E7%A0%81%E5%A6%82%E4%B8%8B"><span class="nav-number">2.</span> <span class="nav-text">今天我们以手机号发送短信为例子 具体代码如下</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9C%A8settings%E4%B8%AD%E7%9A%84INSTALLED-APPS%E9%87%8C%E9%85%8D%E7%BD%AEdjcelery%E4%BB%A5%E5%8F%8A%E6%B6%88%E6%81%AF%E5%88%97%E9%98%9F%E7%9A%84%E5%9C%B0%E5%9D%80"><span class="nav-number">2.1.</span> <span class="nav-text">在settings中的INSTALLED_APPS里配置djcelery以及消息列队的地址</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%9B%E5%BB%BAtasks"><span class="nav-number">2.2.</span> <span class="nav-text">创建tasks</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%9B%E5%BB%BAutils"><span class="nav-number">2.3.</span> <span class="nav-text">创建utils</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%89%8B%E6%9C%BA%E5%8F%B7%E5%8F%91%E9%80%81%E9%AA%8C%E8%AF%81%E7%A0%81"><span class="nav-number">2.4.</span> <span class="nav-text">手机号发送验证码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9C%80%E5%90%8E%E5%90%AF%E5%8A%A8%EF%BC%88%E6%B3%A8%E6%84%8F%E8%A6%81%E4%BF%9D%E8%AF%81redis%E4%B8%BA%E5%BC%80%E5%90%AF%E7%8A%B6%E6%80%81%EF%BC%89"><span class="nav-number">2.5.</span> <span class="nav-text">最后启动（注意要保证redis为开启状态）</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">X y</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/wow/archives/">
        
          <span class="site-state-item-count">23</span>
          <span class="site-state-item-name">المقالات</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">التصنيفات</span>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">الوسوم</span>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-hans">
    <link itemprop="mainEntityOfPage" href="https://single-flower.gitee.io/wow/2021/02/03/zy/celery%E5%BC%82%E6%AD%A5%E6%A1%86%E6%9E%B6(5.0)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/wow/images/avatar.gif">
      <meta itemprop="name" content="X y">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="朵朵最可爱">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          celery异步框架
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">نُشر في</span>

      <time title="أُنشأ: 2021-02-03 10:26:02" itemprop="dateCreated datePublished" datetime="2021-02-03T10:26:02+08:00">2021-02-03</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">عُدل في</span>
        <time title="عُدل: 2021-04-13 15:05:36" itemprop="dateModified" datetime="2021-04-13T15:05:36+08:00">2021-04-13</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">في</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/wow/categories/GIT/" itemprop="url" rel="index"><span itemprop="name">-GIT</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="安装包"><a href="#安装包" class="headerlink" title="安装包"></a>安装包</h2><p>pip3 install Django==2.2</p>
<p>pip3 install celery==4.4.7</p>
<p>pip install redis=3.5.3</p>
<h2 id="今天我们以手机号发送短信为例子-具体代码如下"><a href="#今天我们以手机号发送短信为例子-具体代码如下" class="headerlink" title="今天我们以手机号发送短信为例子 具体代码如下"></a>今天我们以手机号发送短信为例子 具体代码如下</h2><h3 id="在settings中的INSTALLED-APPS里配置djcelery以及消息列队的地址"><a href="#在settings中的INSTALLED-APPS里配置djcelery以及消息列队的地址" class="headerlink" title="在settings中的INSTALLED_APPS里配置djcelery以及消息列队的地址"></a>在settings中的INSTALLED_APPS里配置djcelery以及消息列队的地址</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"># settings.py</span><br><span class="line"><span class="keyword">import</span> djcelery</span><br><span class="line"></span><br><span class="line">djcelery.setup_loader()</span><br><span class="line">BROKER_URL = &#x27;redis://123.57.61.168:6379&#x27;  # 这就是broker消息队列的地址</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="创建tasks"><a href="#创建tasks" class="headerlink" title="创建tasks"></a>创建tasks</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"># tasks.py</span><br><span class="line"><span class="keyword">from</span> celery <span class="keyword">import</span> task</span><br><span class="line"><span class="keyword">from</span> ronglian_sms_sdk <span class="keyword">import</span> SmsSDK</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def SMSinit(ACCOUNT_SID, AUTH_TOKEN, APP_ID):</span><br><span class="line">    <span class="keyword">return</span> SmsSDK(ACCOUNT_SID, AUTH_TOKEN, APP_ID)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">@task</span><br><span class="line">def SMSsend(sms, tid=1, mobile=[], datas=[]):  # .delay</span><br><span class="line">    # 升级成为异步方法</span><br><span class="line">    tid = tid  # 登录验证模版 默认ID为1</span><br><span class="line">    mobile = &#x27;,&#x27;.join(mobile) if len(mobile) &gt; 1 else mobile[0]  # 接收的手机号列表</span><br><span class="line">    datas = datas</span><br><span class="line">    resp = sms.sendMessage(tid, mobile, datas)</span><br></pre></td></tr></table></figure>
<h3 id="创建utils"><a href="#创建utils" class="headerlink" title="创建utils"></a>创建utils</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"># utils.py</span><br><span class="line">rom ronglian_sms_sdk <span class="keyword">import</span> SmsSDK</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class SMS:</span><br><span class="line">    def __init__(self, ACCOUNT_SID, AUTH_TOKEN, APP_ID):</span><br><span class="line">        self.sdk = SmsSDK(ACCOUNT_SID, AUTH_TOKEN, APP_ID)</span><br><span class="line"></span><br><span class="line">    def send(self, tid=<span class="number">1</span>, mobile=[], datas=[]):</span><br><span class="line">        time.sleep(<span class="number">5</span>)</span><br><span class="line">        tid = tid  # 登录验证模版 默认ID为1</span><br><span class="line">        mobile = &#x27;,&#x27;.join(mobile) if len(mobile) &gt; 1 else mobile[0]  # 接收的手机号列表</span><br><span class="line">        datas = datas</span><br><span class="line">        resp = self.sdk.sendMessage(tid, mobile, datas)</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="手机号发送验证码"><a href="#手机号发送验证码" class="headerlink" title="手机号发送验证码"></a>手机号发送验证码</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"># view.py</span><br><span class="line">class PhoneSMS(APIView):</span><br><span class="line">    def post(self, request):</span><br><span class="line">        phone = request.data.get(<span class="string">&#x27;phone&#x27;</span>)</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            User.objects.get(phone=phone)</span><br><span class="line">        except:</span><br><span class="line">            <span class="keyword">return</span> Response(&#123;</span><br><span class="line">                <span class="string">&#x27;code&#x27;</span>: <span class="number">500</span>,</span><br><span class="line">                <span class="string">&#x27;message&#x27;</span>: <span class="string">&#x27;用户不存在，无法发送&#x27;</span></span><br><span class="line">            &#125;)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            # sms = SMS(ACCOUNT_SID, AUTH_TOKEN, APP_ID)</span><br><span class="line">            sms = SMSinit(ACCOUNT_SID, AUTH_TOKEN, APP_ID)</span><br><span class="line">            code = random_code(<span class="number">6</span>)</span><br><span class="line">            r.set(phone, code, <span class="number">60</span>)</span><br><span class="line">            datas = [code, <span class="string">&#x27;60s&#x27;</span>]</span><br><span class="line">            # sms.send(mobile=[phone], datas=datas)</span><br><span class="line">            SMSsend.delay(sms, mobile=[phone], datas=datas)</span><br><span class="line">            # 直接加入消息队列，由celery去管理</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> Response(&#123;</span><br><span class="line">                <span class="string">&#x27;code&#x27;</span>: <span class="number">200</span>,</span><br><span class="line">                <span class="string">&#x27;message&#x27;</span>: <span class="string">&#x27;验证码已发送&#x27;</span></span><br><span class="line">            &#125;)</span><br></pre></td></tr></table></figure>
<h3 id="最后启动（注意要保证redis为开启状态）"><a href="#最后启动（注意要保证redis为开启状态）" class="headerlink" title="最后启动（注意要保证redis为开启状态）"></a>最后启动（注意要保证redis为开启状态）</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python manage.py celery worker</span><br></pre></td></tr></table></figure>
    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/wow/tags/GIT/" rel="tag"># -GIT</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/wow/2021/02/01/zy/%E4%B8%89%E6%96%B9%E6%94%AF%E4%BB%98/" rel="prev" title="三方支付">
                  <i class="fa fa-chevron-left"></i> 三方支付
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/wow/2021/02/10/zy/axios%E5%B0%81%E8%A3%85/" rel="next" title="axios封装">
                  axios封装 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">X y</span>
</div>
  <div class="powered-by">تطبيق الموقع <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a>
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/wow/js/utils.js"></script><script src="/wow/js/motion.js"></script><script src="/wow/js/schemes/muse.js"></script><script src="/wow/js/next-boot.js"></script>

  






  





</body>
</html>
